import { browser } from 'webextension-polyfill-ts';

export async function setvpnStore(data: any, opt?: string[]) {
    const { vpnStore } = await browser.storage.local.get('vpnStore');
    if (opt) {
        data = opt.reduce((acc, curr) => {
            acc[curr] = { ...acc[curr], ...data[curr] };
            return acc;
        }, vpnStore);
    }
    return browser.storage.local.set({
        vpnStore: {
            ...vpnStore,
            ...data,
        },
    });
}

export async function getvpnStore() {
    const result = await browser.storage.local.get('vpnStore');
    return result.vpnStore;
}

export function setConnectIcon(connected: boolean) {
    if (connected) {
        browser.browserAction.setIcon({ path: 'assets/icons/on.png' });
    } else {
        browser.browserAction.setIcon({ path: 'assets/icons/off.png' });
    }
}

export function gotoPage(url: string) {
    browser.tabs.create({ url: url });
}

export const storage = {
    get: (key: string) => {
        return browser.storage.local.get(key);
    },
    set: (items: any) => {
        return browser.storage.local.set(items);
    },
    clear: () => {
        return browser.storage.local.clear();
    },
};

export const localstorage = {
    get: (key: string) => {
        const value: any = localStorage.getItem(key);
        return JSON.parse(value);
    },
    set: (key: string, value: any) => {
        localStorage.setItem(key, JSON.stringify(value));
    },
    clear: () => {
        localStorage.clear();
    },
    remove: (key: string) => {
        localStorage.removeItem(key);
    },
};

export async function errorLog(e: any) {
    return Promise.reject(e.toString());
}

export function isChrome() {
    if (browser.proxy.onProxyError) {
        return true;
    } else {
        return false;
    }
}
